import axios from 'axios'
import vueRouter from '@/router'
import { baseURL } from '@/config'
import { getToken } from '@/libs/util'

class HttpRequest {
    constructor(baseUrl = baseURL) {
        this.baseUrl = baseUrl
    }

    // axios配置
    getInsideConfig() {
        const route = vueRouter?.currentRoute?.value
        const appId = route.params.appId

        const config = {
            baseURL: this.baseUrl,
            headers: {
                Authorization: `Bearer ${getToken()}`,
                APP_ID: appId,
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
        return config
    }

    distroy(url) {
        // 
    }

    interceptors(instance, url) {
        // 请求拦截器
        instance.interceptors.request.use(config => {
            if (config.method.toLowerCase() === 'get') {
                config.data = true // 给data赋值以绕过if判断
                config.headers['Content-Type'] = 'application/json'
            }
            return config
        }, error => Promise.reject(error))
        // 响应拦截器
        instance.interceptors.response.use(res => {
            this.distroy(url)
            const { data } = res
            return data
        }, error => {
            this.distroy(url)
            return Promise.reject(error.response.data)
        })
    }

    request(options) {
        const instance = axios.create()
        const defaultOptions = this.getInsideConfig()
        options = { ...defaultOptions, ...options }
        options.headers = { ...defaultOptions.headers, ...(options.headers || {}) }
        this.interceptors(instance, options.url)
        return instance(options)
    }
}
export default HttpRequest
